import { Spin } from "view-design";
import request from "./request";

/**
 * @description: 下载文件api
 * @param url:下载地址
 * @param data:下载参数
 * @param body:参数是否在body中传递
 * @return Promise
 */
const doenloadFile = (url, data, body) =>
    request({
        url,
        method: "post",
        data: body ? data : "",
        responseType: "blob",
        params: body ? "" : data,
    });
/**
 * @description: 下载文件方法
 * @param url:下载地址
 * @param data:下载参数
 * @param body:参数是否在body中传递
 * @return 文件
 */
export function DOWNLOAD(url, params, body = true) {
    // 加载中效果
    Spin.show({
        render: (h) => {
            return h("div", [
                h("Icon", {
                    class: "spin-icon-load",
                    style: "animation: ani-demo-spin 1s linear infinite;",
                    props: {
                        type: "ios-loading",
                        size: "30",
                    },
                }),
                h("div", "加载中"),
            ]);
        },
    });
    doenloadFile(url, params, body).then((res) => {
        var blob = new Blob([res.data]);
        const temp = res.headers["content-disposition"].split("filename=")[1];
        const fileName = decodeURIComponent(temp);
        var blob = new Blob([res.data]);
        var downloadElement = document.createElement("a");
        var href = window.URL.createObjectURL(blob); // 创建下载的链接
        downloadElement.href = href;
        downloadElement.download = fileName; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
        // 取消加载中
        Spin.hide();
    });
}
